import { createI18n } from 'vue-i18n'

import enUS from './en-US.json' with { type: 'json' }
import zhCN from './zh-CN.json' with { type: 'json' }
import { LocalStorage } from '@/constants/localStorage'
import { Locale } from '@/constants/locale'

const getDefaultLocale = (defaultLocale: Locales): Locales => {
  const locale = localStorage.getItem(LocalStorage.Locale)

  const isSupportedLocale = locale !== null && [Locale.EN, Locale.ZH].includes(locale as Locale)
  if (isSupportedLocale) {
    return locale as Locale
  }

  localStorage.setItem(LocalStorage.Locale, defaultLocale)
  return defaultLocale
}

export const defineMessage = <T extends Record<string, any>>(
  enUS: T,
  zhCN: T
): Record<Locales, T> => ({
  [Locale.EN]: enUS,
  [Locale.ZH]: zhCN
})

/** 方便测试时每次都使用独立的实例 */
export function buildI18n() {
  return createI18n({
    legacy: false,
    globalInjection: false,
    locale: getDefaultLocale(Locale.Default),
    fallbackLocale: Locale.Default,
    messages: defineMessage(enUS, zhCN)
  })
}

export const i18n = buildI18n()
